package com.qf.servlet;

import com.qf.Enity.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        /**
         * 上面拦截的是/* ,即所有路径资源都会被过滤
         * 但是有些路径资源,是不需要登录信息认证
         * 比如: 图片,css,js,html,以及/index.jsp /login /logout 等路径不需要验证
         */
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        String uri = req.getRequestURI( );
        System.out.println("uri = " + uri);
        // 如果是静态资源/登录相关就放行
        if (uri.contains("css") || uri.contains("js") || uri.contains("jpg") || uri.contains("png")
                || uri.contains("index") || uri.contains("login") || uri.contains("logout")) {
            // 放行
            filterChain.doFilter(servletRequest,servletResponse);

        } else { // 其他资源就拦截开始过滤

            HttpSession session = req.getSession( );
            User user = (User) session.getAttribute("user");
            if (user != null) {
                // 放行
                filterChain.doFilter(servletRequest,servletResponse);

            } else {
                // 说明之前没有登录,跳转首页 不放行
                resp.sendRedirect("/index.jsp");
            }
        }

    }

    @Override
    public void destroy() {

    }
}
